<template>
  <div class="h100 systemUserPage">
    <a-row class="systemUserPageRow">
      <a-col :span="5" class="left" v-if="$hasPermission(managePerms.organization.view)">
        <department-tree @clickorg="clickOrg"></department-tree>
      </a-col>
      <a-col :span="19" class="right">
        <user-list @clickbtn="handleUserData" ref="userList"></user-list>
      </a-col>
    </a-row>
  </div>
</template>
<script>
import DepartmentTree from './components/DepartmentTree'
import UserList from './components/UserList'
import EditUser from './components/EditUser'
import EditOrg from './components/EditOrg'
import RelatedModel from './components/RelatedModel'
import ShowRelatedModel from './components/ShowRelatedModel'
import { mapGetters, mapState } from 'vuex'
import { minxinDrawerUse } from '@/utils/mixin'
import { managePerms } from '@/config/permission/index'
import userApi from '@/api/modules/system/user'
import MailSend from '@/views/system/mailsend/mailSend.vue'

const initOrgData = {
  name: '',
  parentId: null,
  id: null,
  remark: ''
}
const initUserData = {
  id: '',
  account: '',
  email: '',
  name: '',
  organizationId: '',
  phone: '',
  remark: '',
  roleIds: []
}
export default {
  mixins: [minxinDrawerUse],
  components: {
    DepartmentTree,
    UserList,
    EditUser,
    EditOrg,
    RelatedModel,
    ShowRelatedModel,
    MailSend
  },
  computed: {
    ...mapGetters(['rightDrawerOPen']),
    ...mapState({
      treeData: (state) => state.org.treeData,
      selectedOrg: (state) => state.org.selectedOrg
    }),
    parentOrgTitle () {
      if (!this.selectedOrg) {
        return
      }
      if (['addOrg', 'addUser'].includes(this.activeAction)) {
        // eslint-disable-next-line consistent-return
        return this.selectedOrg.name
      }
      if (!this.selectedOrg.parentId) {
        // eslint-disable-next-line consistent-return
        return '无'
      }
      // eslint-disable-next-line consistent-return
      return this.getParentOrgTitle(this.treeData)
    }
  },
  data () {
    return {
      managePerms,
      formTitle: this.$t('new') + this.$t('user'),
      // 当前组织
      activeOrg: null,
      editRecord: null,
      activeAction: null
    }
  },
  mounted () {
  },
  methods: {
    clickOrg (action) {
      if (this[action]) {
        this[action]()
        this.activeAction = action
      }
    },
    saveEditUserData (data) {
      const method = data.id ? 'editUserData' : 'addUserData'
      return this.$store.dispatch(method, data)
    },
    saveEditOrgData (data) {
      const method = data.id ? 'editOrgData' : 'addOrgData'
      return this.$store.dispatch(method, data)
    },
    // 邮件推送
    editEmailPush (data) {
      console.log(data.account)
      this.$api.editEmailPush(data)
        .then(() => {
          this.$message.success(this.$t('successfullyOperation'))
          this.removeRightDrawer()
        })
        .finally(() => {
          this.removeRightDrawer()
        })
    },
    // 新建组织
    addOrg () {
      const buttons = this.getRightDrawerFooterButtons({
        key: managePerms.organization.add,
        method: 'saveEditOrgData',
        callback () {
        }
      })
      const vars = {
        time: Date.now(),
        class: 'rightDrawerWithoutCol',
        editRecord: { ...initOrgData, parentId: this.selectedOrg.id }
      }
      this.showRightDrawer(EditOrg, this.$t('new') + this.$t('org'), buttons, 'small', vars)
    },
    // 编辑组织
    editOrg () {
      const buttons = this.getRightDrawerFooterButtons({
        key: managePerms.organization.edit,
        method: 'saveEditOrgData',
        callback () {
        }
      })
      const vars = { time: Date.now(), class: 'rightDrawerWithoutCol', editRecord: { ...this.selectedOrg } }
      this.showRightDrawer(EditOrg, this.$t('edit') + this.$t('org'), buttons, 'small', vars)
    },
    // 调用新建/编辑用户方法
    handleUserData (obj) {
      if (this[obj.type]) {
        this[obj.type](obj.data)
        this.activeAction = obj.type
      }
    },
    // 新建用户
    addUser () {
      const _this = this
      const buttons = this.getRightDrawerFooterButtons({
        key: managePerms.user.add,
        method: 'saveEditUserData',
        callback () {
          _this.refreshUserListData()
        }
      })
      const vars = {
        time: Date.now(),
        class: 'rightDrawerWithoutCol',
        editRecord: { ...initUserData, organizationId: this.selectedOrg.id }
      }
      const subTitle = this.$t('belongTo') + '：' + this.selectedOrg.name
      this.showRightDrawer(EditUser, this.$t('new') + this.$t('user'), buttons, '500px', vars, subTitle)
    },
    // 编辑用户
    editUser (data) {
      const _this = this
      const buttons = this.getRightDrawerFooterButtons({
        key: managePerms.user.edit,
        method: 'saveEditUserData',
        callback () {
          _this.refreshUserListData(false)
        }
      })
      const tempData = {}
      // eslint-disable-next-line no-restricted-syntax
      for (const k in initUserData) {
        if (typeof data[k] !== 'undefined') {
          tempData[k] = data[k]
        }
      }
      tempData.roleIds = data.roles.map((item) => item.id)
      const vars = { time: Date.now(), class: 'rightDrawerWithoutCol', editRecord: tempData }
      this.showRightDrawer(EditUser, this.$t('edit') + this.$t('user'), buttons, 'small', vars)
    },
    // 邮件推送
    pushEmail (data) {
      console.log(data.account, '行内数据')
      const _this = this
      const buttons = this.getRightDrawerFooterButtons({
        // key: managePerms.user.add,
        method: 'editEmailPush',
        callback () {
          _this.refreshUserListData()
        }
      })
      const vars = {
        time: Date.now(),
        class: 'rightDrawerWithoutCol',
        emailPushByAccount: data.account
      }
      this.showRightDrawer(MailSend, this.$t('yjts'), buttons, 'small', vars)
    },
    // 获取当前组织父节点名称
    getParentOrgTitle (data) {
      let title = ''
      for (let i = 0; i < data.length; i = i + 1) {
        if (data[i].id === this.selectedOrg.parentId) {
          return data[i].name
        }
        if (data[i].childOrganizations.length > 0) {
          title = this.getParentOrgTitle(data[i].childOrganizations)
        }
      }
      return title
    },
    // 刷新用户列表数据
    refreshUserListData (isToFirstPage) {
      this.$refs.userList.refreshData(isToFirstPage)
    },
    // 关联车型
    relatedModel (record) {
      const _this = this
      const buttons = this.getRightDrawerFooterButtons({
        key: managePerms.user.edit,
        method: 'saveRelatedModel',
        callback () {
          _this.refreshUserListData(false)
        }
      })
      const vars = {
        class: 'rightDrawerWithoutCol',
        userId: record.id
      }
      const subTitle = this.$t('account') + '：' + record.account
      this.showRightDrawer(RelatedModel, this.$t('relatedModel'), buttons, 'medium', vars/*, subTitle*/)
    },
    // 保存关联车型数据
    saveRelatedModel (data) {
      return userApi.setUserModel(data)
    },
    // 查看关联车型
    lookupRelatedModel (record) {
      const vars = {
        class: 'rightDrawerWithoutCol',
        userId: record.id
      }
      const subTitle = this.$t('account') + '：' + record.account
      this.showRightDrawer(ShowRelatedModel, this.$t('relatedModel'), [], 'medium', vars/*, subTitle*/)
    }
  },
  beforeDestroy () {
    this.$store.commit('resetUserQueryParams')
  }
}
</script>
<style scoped lang="less">
.systemUserPageRow {
  height: 100%;
  > .ant-row {
    height: 100%;
  }
  > .ant-col {
    height: 100%;
    overflow: auto;
  }
  .left {
    padding: 24px 24px 0 24px;
    border-right: 1px solid @borderColor;
  }
}
</style>
